package com.mondo.financialwallet.presentation.ui.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.common.ui.BaseFragment;
import com.example.common.widget.state.NetworkStateLayout;
import com.example.common.widget.state.OnAnewRequestNetworkListener;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.MyTokenListEntity;
import com.mondo.financialwallet.data.entity.TokenTransactionRecordEntity;
import com.mondo.financialwallet.presentation.model.TokenTransactionRecord;
import com.mondo.financialwallet.presentation.event.RequestWalletAssetEvent;
import com.mondo.financialwallet.presentation.ui.activity.TransactionRecordActivity;
import com.mondo.financialwallet.presentation.ui.adapter.TokenTransactionRecordAdapter;
import com.mondo.financialwallet.presentation.ui.window.TypeSelectionPopupWindow;
import com.mondo.financialwallet.presentation.ui.widget.FinalSpacingItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;

/**
 * 代币充值、转账记录
 */
public class TokenTransactionRecordFragment extends BaseFragment
        implements BaseQuickAdapter.OnItemClickListener, OnRefreshLoadmoreListener, OnAnewRequestNetworkListener {

    private static final String
            RECORD_TYPE = "RECORD_TYPE",
            TOKEN_ID = "TOKEN_ID";

    private static final String
            ALL_TYPE = null,
            TRANSFER_OUT_TYPE = "2",
            TRANSFER_TYPE = "1";

    public static Fragment createAllRecord(String tokenId) {
        TokenTransactionRecordFragment fragment = new TokenTransactionRecordFragment();
        Bundle arguments = new Bundle();
        arguments.putString(RECORD_TYPE, ALL_TYPE);
        arguments.putString(TOKEN_ID, tokenId);
        fragment.setArguments(arguments);
        return fragment;
    }

    public static Fragment createTransferRecord(String tokenId) {
        TokenTransactionRecordFragment fragment = new TokenTransactionRecordFragment();
        Bundle arguments = new Bundle();
        arguments.putString(RECORD_TYPE, TRANSFER_TYPE);
        arguments.putString(TOKEN_ID, tokenId);
        fragment.setArguments(arguments);
        return fragment;
    }

    public static Fragment createTransferOutRecord(String tokenId) {
        TokenTransactionRecordFragment fragment = new TokenTransactionRecordFragment();
        Bundle arguments = new Bundle();
        arguments.putString(RECORD_TYPE, TRANSFER_OUT_TYPE);
        arguments.putString(TOKEN_ID, tokenId);
        fragment.setArguments(arguments);
        return fragment;
    }

    @Bind(R.id.divider_view) View mDividerView;
    @Bind(R.id.type_select_layout) View mTypeSelectLayout;
    @Bind(R.id.token_types_layout) View mTokenTypesLayout;
    @Bind(R.id.select_token_type_name_text) TextView mTokenTypeNameTextView;
    @Bind(R.id.select_direction_name_text) TextView mDirectionNameTextView;
    @Bind(R.id.income_expenditure_layout) View mIncomeExpenditureLayout;
    @Bind(R.id.token_transaction_record_list) RecyclerView mTokenTransactionRecordList;
    @Bind(R.id.smart_refresh_layout) SmartRefreshLayout mSmartRefreshLayout;
    @Bind(R.id.network_state_layout) NetworkStateLayout mNetworkStateLayout;

    private int currentPage = 1;
    private String mTokenId, mIncomeType;
    private TokenTransactionRecordAdapter mAdapter;
    private TypeSelectionPopupWindow mTokenTypeWindow, mTokenDirectionWindow;

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_transaction_record;
    }

    @Override
    protected void initActions() {
        // 刷新加载
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(this);

        // 状态布局
        mNetworkStateLayout.setOnAnewRequestNetworkListener(this);

        // 列表
        mAdapter = new TokenTransactionRecordAdapter();
        mAdapter.setOnItemClickListener(this);
        mTokenTransactionRecordList.addItemDecoration(new FinalSpacingItemDecoration());
        mTokenTransactionRecordList.setAdapter(mAdapter);

        // 进行不同操作
        Bundle arguments = getArguments();
        if (arguments == null) {
            displayView_1();

            // 我的货币列表
            requestMyTokenList();
        } else {

            displayView_2(arguments);
        }

        // 请求我的交易记录列表
        requestTransfer();
    }

    private void displayView_1() {
        mTypeSelectLayout.setVisibility(View.VISIBLE);
        mDividerView.setVisibility(View.VISIBLE);

        // 显示我的token
        mTokenTypesLayout.setOnClickListener(v -> showTokenTypesWindow());

        // 买入/卖出
        mIncomeExpenditureLayout.setOnClickListener(v -> showIncomeExpenditureWindow());
    }

    private void displayView_2(Bundle arguments) {
        mTokenId = arguments.getString(TOKEN_ID);
        mIncomeType = arguments.getString(RECORD_TYPE);
    }

    // 请求新的数据
    private void requestNewData() {
        currentPage = 1;
        requestTransfer();
    }

    // 请求所有交易
    private void requestTransfer() {
        if (currentPage == 1){
            mNetworkStateLayout.loadingNetwork();
        }

        DataRepository.get().tokenTransactionRecord(currentPage, mTokenId, mIncomeType, result -> {
            if (mSmartRefreshLayout != null){
                mSmartRefreshLayout.finishRefresh();
                mSmartRefreshLayout.finishLoadmore();
            }

            if (result.isSuccess()) {
                TokenTransactionRecordEntity.DataBean data = result.getData();
                List<TokenTransactionRecordEntity.DataBean.ItemsBean> items = data.getItems();
                if (items == null || items.isEmpty()){
                    if (currentPage == 1){
                        mNetworkStateLayout.emptyNetwork();
                    }

                } else {
                    mNetworkStateLayout.successNetwork();

                    if (currentPage == 1){
                        mAdapter.setNewData(transformData(items));
                    } else if (currentPage > 1 && items.size() > 0){
                        mAdapter.addData(transformData(items));
                    }
                }

            } else if (currentPage == 1){
                mNetworkStateLayout.errorNetwork(result.getMsg());
            }
        });
    }

    private List<TokenTransactionRecord> transformData(
            List<TokenTransactionRecordEntity.DataBean.ItemsBean> list) {
        List<TokenTransactionRecord> recordList = new ArrayList<>();
        if (list != null) {
            for (TokenTransactionRecordEntity.DataBean.ItemsBean item : list) {
                recordList.add(new TokenTransactionRecord(
                        item.getToken_name(),
                        item.getIncome(),
                        item.getCreate_time(),
                        String.valueOf(item.getNumber()),
                        item.getFrom(),
                        item.getTo(),
                        item.getBlock_height(),
                        item.getRemark(),
                        item.getTx(),
                        item.getStatusX(),
                        item.getFee()
                ));
            }
        }

        return recordList;
    }

    private void requestMyTokenList() {
        DataRepository.get().myTokenList(result -> {
            if (result.isSuccess()) {
                List<MyTokenListEntity.DataBean> data = result.getData();
                List<TypeSelectionPopupWindow.Type> types = new ArrayList<>();
                types.add(new TypeSelectionPopupWindow.Type(null, "全部"));
                for (MyTokenListEntity.DataBean datum : data) {
                    types.add(new TypeSelectionPopupWindow.Type(
                            String.valueOf(datum.getToken_id()),
                            datum.getTitle_en()
                    ));
                }

                // 货币类型
                mTokenTypeWindow = new TypeSelectionPopupWindow(getContext(), types);
                mTokenTypeWindow.setOnClickListener(type -> {
                    mTokenId = type.getId();
                    mTokenTypeNameTextView.setText(type.getText());
                    requestNewData();
                });

                // 方向
                mTokenDirectionWindow = new TypeSelectionPopupWindow(getContext(), Arrays.asList(
                        new TypeSelectionPopupWindow.Type(null, "全部"),
                        new TypeSelectionPopupWindow.Type(TRANSFER_TYPE, "转入"),
                        new TypeSelectionPopupWindow.Type(TRANSFER_OUT_TYPE, "转出")
                ));

                mTokenDirectionWindow.setOnClickListener(type -> {
                    mIncomeType = type.getId();
                    mDirectionNameTextView.setText(type.getText());
                    requestNewData();
                });
            }
        });
    }

    private void showIncomeExpenditureWindow() {
        if (mTokenDirectionWindow != null) {
            mTokenDirectionWindow.show(mIncomeExpenditureLayout);
        }
    }

    // 显示我的Token
    private void showTokenTypesWindow() {
        if (mTokenTypeWindow != null) {
            mTokenTypeWindow.show(mTypeSelectLayout);
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        TransactionRecordActivity.launch(getContext(), mAdapter.getItem(position));
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        currentPage = currentPage + 1;
        requestTransfer();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        requestTransfer();
    }

    @Subscribe
    public void requestWalletAssetEvent(RequestWalletAssetEvent event){
        requestTransfer();
    }

    @Override
    public void onAnewRequestNetwork() {
        requestTransfer();
    }
}
